package me.itsoo.artemis.framework.aop.util;

import lombok.extern.slf4j.Slf4j;
import me.itsoo.artemis.framework.core.collect.Kv;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static me.itsoo.artemis.framework.aop.util.BeggarsLexicalAnalyzer.SimpleFiniteState;

/**
 * KeyProcessor
 *
 * @author zxy
 */
@Slf4j
public class KeyProcessor {

    private static final Map<String, String> KEYS_CACHE = new ConcurrentHashMap<>(32);

    /*private static final ExpressionParser PARSER = new SpelExpressionParser();

    private static final ParserContext PARSER_CONTEXT = ParserContext.TEMPLATE_EXPRESSION;

    public static final String EXPRESSION_DELIMITER_PREFIX = PARSER_CONTEXT.getExpressionPrefix();

    public static final String EXPRESSION_DELIMITER_SUFFIX = PARSER_CONTEXT.getExpressionSuffix();*/


    public static String getCacheKey(String key, Map<String, Object> params) {
        String parsedKey = getCacheKey(key);
        log.info("Source cache-key: [{}] ===> Parsed cache-key: [{}]", key, parsedKey);
        /*StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariables(params);
        return PARSER.parseExpression(parsedKey, PARSER_CONTEXT).getValue(context, String.class);*/
        return null;
    }

    static String getCacheKey(String key) {
        StringBuilder result = new StringBuilder();
        int i = 0, j = i;
        /*while ((i = key.indexOf(EXPRESSION_DELIMITER_PREFIX, i)) != -1) {
            i += EXPRESSION_DELIMITER_PREFIX.length();
            // no expression template delimiter
            result.append(key, j, i);
            j = key.indexOf(EXPRESSION_DELIMITER_SUFFIX, i);
            result.append(getExpressionLockKey(key.substring(i, j)));
            i = j;
        }*/

        return result.append(key.substring(j)).toString();
    }

    private static String getExpressionLockKey(String key) {
        return KEYS_CACHE.computeIfAbsent(key, KeyProcessor::getExpressionVarLockKey);
    }

    private static String getExpressionVarLockKey(String key) {
        StringBuilder result = new StringBuilder(key.length() + 8);
        for (Kv<SimpleFiniteState, String> kv : BeggarsLexicalAnalyzer.parseKey(key)) {
            if (kv.getKey().isVariable()) {
                result.append('#');
            }

            result.append(kv.getValue());
        }

        return result.toString();
    }
}
